package org.luckyjourney.config;

import lombok.extern.slf4j.Slf4j;
import org.luckyjourney.entity.booking.Orders;
import org.luckyjourney.mapper.booking.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
@Component
@Slf4j
//订单支付超时处理
public class OrderTask {
    @Autowired
    OrdersMapper ordersMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", new Date());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-30);


        // select * from orders where status = 1 and order_time < 当前时间-15分钟
        List<Orders> ordersList = ordersMapper.findByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("支付超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                ordersMapper.update(order);
            });
        }
    }
}
